
package com.insigma.business.qrcode.soldier._provider.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.cache.Cache;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import com.insigma.business.qrcode.common.converter.SoldierUnemploymentRegistrationInfoProviderConverter;
import com.insigma.business.qrcode.common.dao.CommonAdminAreaDO;
import com.insigma.business.qrcode.common._provider.CommonAdminAreaProvider;
import com.insigma.business.qrcode.common.service.CommonAdminAreaService;
import com.insigma.business.qrcode.common.service.GovOrgService;
import com.insigma.business.qrcode.common.template.BasePagingResponse;
import com.insigma.business.qrcode.common.template.MemCacheManager;
import com.insigma.business.qrcode.common.util.AdminAreaCodeUtils;
import com.insigma.business.qrcode.common.util.BizCheckUtil;
import com.insigma.business.qrcode.common.util.BizException;
import com.insigma.business.qrcode.common.util.ResponseUtils;
import com.insigma.business.qrcode.common.vo.BaseDeleteRequest;
import com.insigma.business.qrcode.common.vo.BaseResponse;
import com.insigma.business.qrcode.intell.dto.CompanyEntryApplyDTO;
import com.insigma.business.qrcode.intell.dto.CompanyEntryApplySearchRequest;
import com.insigma.business.qrcode.intell._consumer.SceneConsumer;
import com.insigma.business.qrcode.intell.util.PageUtils;
import com.insigma.business.qrcode.soldier._provider.*;
import com.insigma.business.qrcode.soldier.dto.*;
import com.insigma.business.qrcode.soldier.dto.gov.BaseProviderImpl;
import com.insigma.business.qrcode.common.template.area.ScenarioCodeEnum;
import com.insigma.business.qrcode.common.template.area.ServiceCallback;
import com.insigma.business.qrcode.soldier.entity.*;
import com.insigma.business.qrcode.soldier.request.*;
import com.insigma.business.qrcode.soldier.service.*;
import com.insigma.business.qrcode.soldier.util.RequestSetUtils;
import com.insigma.business.qrcode.soldier.util.ThreadPoolManager;
import com.insigma.business.qrcode.job.dto.ExpectedInfoRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.logging.log4j.util.Strings;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.insigma.business.qrcode.soldier.util.ThirdPartyDealUtils;
import com.insigma.business.qrcode.common.dto.ErrorCodeEnum;
import com.insigma.business.qrcode.job.dto.JobCandidateResumeDTO;

import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;


@Slf4j
@Service
@Component("soldierUnemploymentRegistrationInfoProvider")
public class SoldierUnemploymentRegistrationInfoProviderImpl extends BaseProviderImpl implements SoldierUnemploymentRegistrationInfoProvider {

    @Autowired
    private CommonTmpInfoService commonTmpInfoService;

    @Autowired
    private SoldierUnemploymentRegistrationInfoService soldierUnemploymentRegistrationInfoService;

    @Autowired
    private SoldierRegistrationHistoryService soldierRegistrationHistoryService;

    @Autowired
    private SoldierBasicInfoService soldierBasicInfoService;

    @Autowired
    private SoldierBasicInfoProvider soldierBasicInfoProvider;

    @Autowired
    private GovMessageProvider govMessageProvider;

    @Autowired
    private CareSoldierEmploymentAssistanceService careSoldierEmploymentAssistanceService;

    @Autowired
    private SceneConsumer sceneConsumer;

    @Autowired
    private SoldierTpAllService soldierTpAllService;

    @Autowired
    private SoldierTpAllProvider soldierTpAllProvider;

    @Autowired
    private GovOrgService govOrgService;

    @Autowired
    private CommonAdminAreaService commonAdminAreaService;

    @Autowired
    private CommonAuthInfoProvider commonAuthInfoProvider;

    @Autowired
    private ThirdPartyService thirdPartyService;

    Cache<String, Object> areaCache = MemCacheManager.getInstance();

    @Autowired
    private CommonAdminAreaProvider commonAdminAreaProvider;


    @Autowired
    private IrsService irsService;

    private String GTLDZ = "个体劳动者";


    @Override
    public BasePagingResponse<List<SoldierUnemploymentRegistrationInfoDTO>> searchSoldierUnemploymentRegistrationInfo(final SoldierUnemploymentRegistrationInfoSearchRequest searchRequest) {

        final BasePagingResponse<List<SoldierUnemploymentRegistrationInfoDTO>> basePagingResponse = new BasePagingResponse<>();
        serviceTemplate.execute(basePagingResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(searchRequest, "查询分页SoldierUnemploymentRegistrationInfo的请求参数不能为空");
            }

            @Override
            public void executeService() {
                final SoldierUnemploymentRegistrationInfoBSearcher soldierUnemploymentRegistrationInfoBSearcher = SoldierUnemploymentRegistrationInfoProviderConverter.convertRequestSO2Searcher(searchRequest);
                if (Strings.isNotBlank(soldierUnemploymentRegistrationInfoBSearcher.getAdminAreaCode())) {
                    soldierUnemploymentRegistrationInfoBSearcher.setAdminAreaCode(AdminAreaCodeUtils.getCutdAreaCode(soldierUnemploymentRegistrationInfoBSearcher.getAdminAreaCode()));
                }
                final List<SoldierUnemploymentRegistrationInfoDO> soldierUnemploymentRegistrationInfoDOList = soldierUnemploymentRegistrationInfoService.search(soldierUnemploymentRegistrationInfoBSearcher);
                final List<SoldierUnemploymentRegistrationInfoDTO> soldierUnemploymentRegistrationInfoDTOList = SoldierUnemploymentRegistrationInfoProviderConverter.convertResponseDOList2DTOList(soldierUnemploymentRegistrationInfoDOList);
                if (!CollectionUtils.isEmpty(soldierUnemploymentRegistrationInfoDTOList)) {
                    for (SoldierUnemploymentRegistrationInfoDTO item : soldierUnemploymentRegistrationInfoDTOList) {
                        item.setAreaValue(getCachedAreaValue(item.getIdCardNo()));

                        if (UnemploymentProcessStatusEnum.INIT.name().equals(item.getStatus()) ||
                                UnemploymentProcessStatusEnum.UNEMPLOYMENT.name().equals(item.getStatus())) {
                            item.setColour("red");
                        } else if (UnemploymentProcessStatusEnum.NO_NEED.name().equals(item.getStatus())
                                || UnemploymentProcessStatusEnum.EMPLOYMENT_VISIT.name().equals(item.getStatus())
                                || UnemploymentProcessStatusEnum.EMPLOYMENT_SOCIAL.name().equals(item.getStatus())) {
                            item.setColour("yellow");
                        } else if (UnemploymentProcessStatusEnum.CANCEL.name().equals(item.getStatus())) {
                            item.setColour("grey");
                        } else {
                            item.setColour("green");
                        }


                        if (UnemploymentProcessStatusEnum.EMPLOYMENT_VISIT.name().equals(item.getStatus())) {
                            Date visitDatetime = item.getVisitDatetime();
                            if (visitDatetime != null) {
                                ThreadPoolManager.getInstance().submit(new Runnable() {
                                    @Override
                                    public void run() {
                                        String lastSocial = soldierTpAllProvider.getLastSocial(item.getIdCardNo());
                                        if (Strings.isNotBlank(lastSocial)) {
                                            String visitTimeStr = DateFormatUtils.format(visitDatetime, "YYYY-MM-DD");
                                            if (lastSocial.compareTo(visitTimeStr) > 0) {
                                                SoldierUnemploymentRegistrationInfoDO registrationInfoDO = soldierUnemploymentRegistrationInfoService.get(item.getId());
                                                registrationInfoDO.setEmploymentDatetime(new Date());
                                                registrationInfoDO.setStatus(UnemploymentProcessStatusEnum.EMPLOYMENT.name());
                                                soldierUnemploymentRegistrationInfoService.update(registrationInfoDO);
                                            }
                                        }
                                    }
                                });
                            }
                        }
                    }
                }

                ResponseUtils.buildSuccessPagingResponse(basePagingResponse, soldierUnemploymentRegistrationInfoDTOList, searchRequest, soldierUnemploymentRegistrationInfoBSearcher.getTotalCount());
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_UNEMPLOYMENT_REGISTRATION_INFO_SEARCH;
            }
        });

        return basePagingResponse;
    }

    private String getCachedAreaValue(String idCardNo) {
        String key = "AREA:CODE:" + idCardNo;
        try {
            Object o = areaCache.get(key, new Callable<String>() {
                @Override
                public String call() throws Exception {
                    SoldierBasicInfoDO byIdCardNo = soldierBasicInfoService.getByIdCardNo(idCardNo);
                    if (byIdCardNo == null) {
                        return "";
                    }
                    String areaCode = byIdCardNo.getResidentAdminAreaCode();
                    int levelLength = AdminAreaCodeUtils.getLevelLength(4);
                    areaCode = AdminAreaCodeUtils.fillAreaCode(areaCode.substring(0, levelLength));
                    CommonAdminAreaDO commonAdminAreaDO = commonAdminAreaService.get(areaCode);
                    if (commonAdminAreaDO == null) {
                        return "";
                    }
                    return commonAdminAreaDO.getFullValuePath();
                }
            });
            return (String) o;
        } catch (ExecutionException e) {
            log.error("缓存失败:{}", e);
        }
        return null;
    }

    @Override
    public BasePagingResponse<List<SoldierUnemploymentRegistrationInfoDTO>> listAllUnemploymentSolider(SoldierUnemploymentRegistrationInfoSearchRequest request) {

        final SoldierUnemploymentRegistrationInfoBSearcher soldierUnemploymentRegistrationInfoBSearcher = SoldierUnemploymentRegistrationInfoProviderConverter.convertRequestSO2Searcher(request);
        soldierUnemploymentRegistrationInfoBSearcher.setStatusList(Lists.newArrayList(UnemploymentProcessStatusEnum.UNEMPLOYMENT.name(), UnemploymentProcessStatusEnum.RECOMMEND.name()));

        List<SoldierUnemploymentRegistrationInfoDO> soldierUnemploymentRegistrationInfoDOList = soldierUnemploymentRegistrationInfoService.listAllUnemploymentSolider(soldierUnemploymentRegistrationInfoBSearcher);
        final List<SoldierUnemploymentRegistrationInfoDTO> soldierUnemploymentRegistrationInfoDTOList = SoldierUnemploymentRegistrationInfoProviderConverter.convertResponseDOList2DTOList(soldierUnemploymentRegistrationInfoDOList);
        return ResponseUtils.buildSuccessPagingResponse(soldierUnemploymentRegistrationInfoDTOList, soldierUnemploymentRegistrationInfoBSearcher);
    }


    @Override
    public BaseResponse<SoldierUnemploymentRegistrationInfoDTO> getSoldierUnemploymentRegistrationInfo(final BaseGetRequest baseGetRequest) {

        final BaseResponse<SoldierUnemploymentRegistrationInfoDTO> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(baseGetRequest, "获取单条SoldierUnemploymentRegistrationInfo的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String) baseGetRequest.getId(), "id不能为空");
            }

            @Override
            public void executeService() {
                final SoldierUnemploymentRegistrationInfoDO soldierUnemploymentRegistrationInfoDO = soldierUnemploymentRegistrationInfoService.get((String) baseGetRequest.getId());
                final SoldierUnemploymentRegistrationInfoDTO remoteObj = SoldierUnemploymentRegistrationInfoProviderConverter.convertResponseDO2DTO(soldierUnemploymentRegistrationInfoDO);
                ResponseUtils.setupSuccessResponse(baseResponse, remoteObj);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_UNEMPLOYMENT_REGISTRATION_INFO_GET;
            }
        });
        return baseResponse;
    }


    @Transactional
    @Override
    public BaseResponse<String> insertSoldierUnemploymentRegistrationInfo(final SoldierUnemploymentRegistrationInfoInsertRequest insertRequest) {


        BizCheckUtil.checkNotNull(insertRequest, "新增SoldierUnemploymentRegistrationInfo的请求参数不能为空");
        List<SoldierUnemploymentRegistrationInfoDO> regList = soldierUnemploymentRegistrationInfoService.getByIdCardNo(insertRequest.getIdCardNo());
        if (!CollectionUtils.isEmpty(regList)) {
            for (SoldierUnemploymentRegistrationInfoDO registrationInfoDO : regList) {
                String status = registrationInfoDO.getStatus();
                BizCheckUtil.checkIsTrue(!(status.equals(UnemploymentProcessStatusEnum.RECOMMEND.name())
                        || status.equals(UnemploymentProcessStatusEnum.UNEMPLOYMENT.name())
                        || status.equals(UnemploymentProcessStatusEnum.INIT.name())), "已存在失业登记");
            }
        }


        SoldierBasicInfoDO byIdCardNo = soldierBasicInfoService.getByIdCardNo(insertRequest.getIdCardNo());
        BizCheckUtil.checkNotNull(byIdCardNo, "还未获得杭州老兵码");

        final SoldierUnemploymentRegistrationInfoDO soldierUnemploymentRegistrationInfoDO = SoldierUnemploymentRegistrationInfoProviderConverter.convertRequestIO2DO(insertRequest);
        soldierUnemploymentRegistrationInfoService.insert(soldierUnemploymentRegistrationInfoDO);

        SoldierRegistrationHistoryDO historyDO = new SoldierRegistrationHistoryDO();
        historyDO.setRegistrationId(soldierUnemploymentRegistrationInfoDO.getId());
        historyDO.setIdCardNo(insertRequest.getIdCardNo());
        historyDO.setStatus(soldierUnemploymentRegistrationInfoDO.getStatus());
        historyDO.setRealName(soldierUnemploymentRegistrationInfoDO.getRealName());
        historyDO.setType(RegistrationHistoryTypeEnum.UNEMPLOYMENT.name());
        historyDO.setNote("失业登记");
        historyDO.setRemark("失业登记");
        historyDO.setDealType(UnemploymentRegistrationTypeEnum.INITIATIVE.name());
        historyDO.setDealTime(new Date());
        soldierRegistrationHistoryService.insert(historyDO);


        String today = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        List<CareSoldierEmploymentAssistanceDO> todayVisitInfos = careSoldierEmploymentAssistanceService.listByIdCardNoAndDate(insertRequest.getIdCardNo(), today);
        if (!CollectionUtils.isEmpty(todayVisitInfos)) {
            for (CareSoldierEmploymentAssistanceDO todayVisitInfo : todayVisitInfos) {
                String status = soldierUnemploymentRegistrationInfoDO.getStatus();
                String visitEmploymentStatus = todayVisitInfo.getEmploymentStatus();
                if (UnemploymentProcessStatusEnum.INIT.name().equals(status)) {
                    if ("有就业需求".equals(visitEmploymentStatus)) {
                        soldierUnemploymentRegistrationInfoDO.setStatus(UnemploymentProcessStatusEnum.UNEMPLOYMENT.name());
                    } else if ("推荐中".equals(visitEmploymentStatus)) {
                        soldierUnemploymentRegistrationInfoDO.setStatus(UnemploymentProcessStatusEnum.UNEMPLOYMENT.name());
                    } else if ("暂无就业需求".equals(visitEmploymentStatus)) {
                        soldierUnemploymentRegistrationInfoDO.setStatus(UnemploymentProcessStatusEnum.NO_NEED.name());
                    } else if ("已就业".equals(visitEmploymentStatus)) {
                        soldierUnemploymentRegistrationInfoDO.setStatus(UnemploymentProcessStatusEnum.EMPLOYMENT_VISIT.name());
                        soldierUnemploymentRegistrationInfoDO.setEmploymentDatetime(new Date());
                    }
                } else if (UnemploymentProcessStatusEnum.UNEMPLOYMENT.name().equals(status) || UnemploymentProcessStatusEnum.RECOMMEND.name().equals(status)) {
                    if ("已就业".equals(visitEmploymentStatus)) {
                        soldierUnemploymentRegistrationInfoDO.setStatus(UnemploymentProcessStatusEnum.EMPLOYMENT_VISIT.name());
                        soldierUnemploymentRegistrationInfoDO.setEmploymentDatetime(new Date());
                    } else if ("暂无就业需求".equals(visitEmploymentStatus)) {
                        soldierUnemploymentRegistrationInfoDO.setStatus(UnemploymentProcessStatusEnum.EMPLOYMENT_VISIT.name());
                        soldierUnemploymentRegistrationInfoDO.setEmploymentDatetime(new Date());
                    }
                } else {
                    continue;
                }

                soldierUnemploymentRegistrationInfoDO.setVisited(true);
                soldierUnemploymentRegistrationInfoDO.setInitStatus("VISIT");
                soldierUnemploymentRegistrationInfoService.update(soldierUnemploymentRegistrationInfoDO);
                log.info("完成对失业退役军人的走访：{}", todayVisitInfo);

                SoldierRegistrationHistoryDO todayHistoryDO = new SoldierRegistrationHistoryDO();
                todayHistoryDO.setRegistrationId(soldierUnemploymentRegistrationInfoDO.getId());
                todayHistoryDO.setIdCardNo(soldierUnemploymentRegistrationInfoDO.getIdCardNo());
                todayHistoryDO.setRealName(soldierUnemploymentRegistrationInfoDO.getRealName());
                todayHistoryDO.setDealType(UnemploymentRegistrationTypeEnum.INITIATIVE.name());
                todayHistoryDO.setNote(todayVisitInfo.getType());
                todayHistoryDO.setRemark(todayVisitInfo.getRemark());
                todayHistoryDO.setDealTime(todayVisitInfo.getDealedFinishDatetime());
                soldierRegistrationHistoryService.insert(historyDO);
            }
        }


        return ResponseUtils.buildSuccessResponse(soldierUnemploymentRegistrationInfoDO.getId()
        );
    }

    @Override
    public BaseResponse<String> insertSoldierUnemploymentRegistrationInfoByGov(SoldierUnemploymentRegistrationInfoInsertRequest insertRequest) {

        BizCheckUtil.checkNotNull(insertRequest, "新增SoldierUnemploymentRegistrationInfo的请求参数不能为空");

        final SoldierUnemploymentRegistrationInfoDO soldierUnemploymentRegistrationInfoDO = SoldierUnemploymentRegistrationInfoProviderConverter.convertRequestIO2DO(insertRequest);
        soldierUnemploymentRegistrationInfoService.insert(soldierUnemploymentRegistrationInfoDO);

        SoldierRegistrationHistoryDO historyDO = new SoldierRegistrationHistoryDO();
        historyDO.setRegistrationId(soldierUnemploymentRegistrationInfoDO.getId());
        historyDO.setIdCardNo(insertRequest.getIdCardNo());
        historyDO.setStatus(soldierUnemploymentRegistrationInfoDO.getStatus());
        historyDO.setRealName(soldierUnemploymentRegistrationInfoDO.getRealName());
        historyDO.setType(RegistrationHistoryTypeEnum.UNEMPLOYMENT.name());
        historyDO.setNote("工作人员 失业登记");
        historyDO.setRemark("工作人员 失业登记");
        historyDO.setDealType(UnemploymentRegistrationTypeEnum.INITIATIVE.name());
        historyDO.setDealTime(new Date());
        soldierRegistrationHistoryService.insert(historyDO);
        return ResponseUtils.buildSuccessResponse("success");
    }

    @Override
    public BaseResponse<String> importUnemploymentSoldier(SoldierUnemploymentRegistrationInfoInsertRequest request) {


        ThreadPoolManager.getInstance().submit(new Runnable() {
            @Override
            public void run() {
                importRsUnemploymentSoldier();
            }
        });
        return ResponseUtils.buildSuccessResponse("处理中");
    }

    @Override
    public void importRsUnemploymentSoldier() {
        int page = 1;
        Date date = org.apache.commons.lang3.time.DateUtils.addMonths(new Date(), -12);
        String startCalDateTime = DateUtil.formatDate(date, "yyyy-MM");
        int loop = 1;
        int oneYearNum = 1;
        int lost = 1;

        SoldierTpAllBSearcher searcher = new SoldierTpAllBSearcher(page++, 1000);
        List<SoldierTpAllDO> unemploymentRegistrationList = unemploymentRegistrationList = soldierTpAllService.searchUnemploymentRegistration(searcher);

        do {
            for (SoldierTpAllDO soldierTpAllDO : unemploymentRegistrationList) {

                try {
                    String unemploymentRegistration = soldierTpAllDO.getUnemploymentRegistration();
                    if (Strings.isNotBlank(unemploymentRegistration)) {
                        List<UnemploymentRegistrationEntity> unemploymentRegistrationEntities = JSONArray.parseArray(unemploymentRegistration, UnemploymentRegistrationEntity.class);
                        for (UnemploymentRegistrationEntity unemploymentRegistrationEntity : unemploymentRegistrationEntities) {
                            String lostJobTime = unemploymentRegistrationEntity.getAae044();
                            if (lostJobTime.compareTo(startCalDateTime) > 0) {

                                if ("有效".equals(unemploymentRegistrationEntity.getAae100())) {

                                    if (soldierTpAllDO.isSocialSecurityFlag()) {
                                        List<InsuredInfoEntity> insuredInfoEntities = ThirdPartyDealUtils.fileSocialSecurity(soldierTpAllDO.getSocialSecurity());
                                        if (CollectionUtils.isEmpty(insuredInfoEntities)) {
                                            break;
                                        }
                                        InsuredInfoEntity lastOne = insuredInfoEntities.get(0);
                                        String aae036 = lastOne.getAae036();

                                        if (aae036.compareTo(lostJobTime) < 0) {


                                            String idCardNo = soldierTpAllDO.getIdCardNo();
                                            insertUnemploySoldierRegistration(idCardNo, "失业时间：" + lostJobTime, "人社失业登记：" + lostJobTime, UnemploymentSourceTypeEnum.REGISTRATION.name());
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("错误：{}", e);
                }

            }
            searcher = new SoldierTpAllBSearcher(page++, 1000);
            unemploymentRegistrationList = soldierTpAllService.searchUnemploymentRegistration(searcher);
        } while (!CollectionUtils.isEmpty(unemploymentRegistrationList));

        log.info("导入失业的人员 end");
    }

    @Override
    public BaseResponse<String> importGtldzSoldier(SoldierUnemploymentRegistrationInfoInsertRequest request) {

        BizCheckUtil.checkNotBlank(request.getAdminAreaCode(), "地区码不能为空");
        ThreadPoolManager.getInstance().submit(new Runnable() {
            @Override
            public void run() {
                importGtLDUnemploymentSoldier(request.getAdminAreaCode());
            }

        });

        return ResponseUtils.buildSuccessResponse("处理中");
    }

    @Override
    public void importGtLDUnemploymentSoldier(String adminAreaCode) {
        int page = 1;
        int loop = 1;
        int gtNum = 1;

        SoldierTpAllBSearcher searcher = new SoldierTpAllBSearcher(page++, 2000);
        searcher.setAdminAreaCode(adminAreaCode);
        List<SoldierTpAllDO> soldierTpAllDOS = soldierTpAllService.searchSocialSecurityInfo(searcher);

        while (!CollectionUtils.isEmpty(soldierTpAllDOS)) {
            for (SoldierTpAllDO soldierTpAllDO : soldierTpAllDOS) {

                List<SoldierUnemploymentRegistrationInfoDO> registrationInfoDOS = soldierUnemploymentRegistrationInfoService.getByIdCardNoWithDeleted(soldierTpAllDO.getIdCardNo());
                if (!CollectionUtils.isEmpty(registrationInfoDOS)) {
                    continue;
                }

                if (soldierTpAllDO.isSocialSecurityFlag()) {
                    List<InsuredInfoEntity> insuredInfoEntities = ThirdPartyDealUtils.fileSocialSecurity(soldierTpAllDO.getSocialSecurity());
                    if (CollectionUtils.isEmpty(insuredInfoEntities)) {
                        continue;
                    }
                    InsuredInfoEntity lastOne = insuredInfoEntities.get(0);
                    String lastTime = lastOne.getAae036();

                    if (GTLDZ.equals(lastOne.getAab004())) {

                        boolean b = checkSameMonthHasCompanySocial(insuredInfoEntities, lastTime);
                        if (!b) {

                            if (isHasProvinceSocialStatusAndNotGtldz(soldierTpAllDO.getIdCardNo(), soldierTpAllDO.getNickName())) {
                                continue;
                            }

                            String idCardNo = soldierTpAllDO.getIdCardNo();
                            insertUnemploySoldierRegistration(idCardNo, "个体劳动者,上次社保时间：" + lastTime, "个体劳动者,上次社保时间：" + lastTime, UnemploymentSourceTypeEnum.INDIVIDUAL_PAYMENT.name());

                        } else {
                            log.info("导入个体劳动者，判断为社保重复，企业缴费：{}", soldierTpAllDO);
                        }
                    }
                }
            }
            searcher = new SoldierTpAllBSearcher(page++, 2000);
            searcher.setAdminAreaCode(adminAreaCode);
            soldierTpAllDOS = soldierTpAllService.searchSocialSecurityInfo(searcher);
        }
        log.info("导入个体劳动者 end");
    }

    @Override
    public String getCompanySocialNotGtldz(String socialSecurity) {
        if (Strings.isBlank(socialSecurity)) {
            return null;
        }
        List<InsuredInfoEntity> insuredInfoEntities = ThirdPartyDealUtils.fileSocialSecurity(socialSecurity);
        if (CollectionUtils.isEmpty(insuredInfoEntities)) {
            return null;
        }
        InsuredInfoEntity lastOne = insuredInfoEntities.get(0);
        String lastTime = lastOne.getAae036();

        String month = lastTime.substring(0, 7);

        List<InsuredInfoEntity> result = insuredInfoEntities.stream().filter(s -> s.getAae036().startsWith(month)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(result)) {
            return "";
        }

        String company = null;
        for (InsuredInfoEntity insuredInfoEntity : result) {
            if (!GTLDZ.equals(insuredInfoEntity.getAab004())) {
                return insuredInfoEntity.getAab004();
            }
        }
        return company;
    }

    private boolean isHasProvinceSocialStatusAndNotGtldz(String idCardNo, String realName) {
        List<SocialSecurityEntity> socialSecurityEntities = irsService.querySocialSecurity(idCardNo, realName);
        if (CollectionUtils.isEmpty(socialSecurityEntities)) {
            return false;
        }

        for (SocialSecurityEntity socialSecurityEntity : socialSecurityEntities) {
            if ("1".equals(socialSecurityEntity.getAac031())) {
                if (!GTLDZ.equals(socialSecurityEntity.getAab004())) {
                    return true;
                }
            }
        }
        return false;
    }


    private boolean checkSameMonthHasCompanySocial(List<InsuredInfoEntity> insuredInfoEntities, String lastTime) {
        if (Strings.isBlank(lastTime)) {
            return false;
        }

        String month = lastTime.substring(0, 7);

        List<InsuredInfoEntity> result = insuredInfoEntities.stream().filter(s -> s.getAae036().startsWith(month)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(result)) {
            return true;
        }

        for (InsuredInfoEntity insuredInfoEntity : result) {
            if (!GTLDZ.equals(insuredInfoEntity.getAab004())) {
                return true;
            }
        }
        return false;
    }


    @Override
    public BaseResponse<String> importWithdrawSoldier(SoldierUnemploymentRegistrationInfoInsertRequest request) {

        BizCheckUtil.checkNotBlank(request.getAdminAreaCode(), "地区码不能为空");
        ThreadPoolManager.getInstance().submit(new Runnable() {
            @Override
            public void run() {
                importDJUnemploymentSoldier(request.getAdminAreaCode());
            }
        });

        return ResponseUtils.buildSuccessResponse("处理中");
    }

    @Override
    public void importDJUnemploymentSoldier(String adminAreaCode) {
        int count = 1;
        int page = 1;
        int studentNum = 1;
        int duanjiaoNum = 1;
        Map<String, NumberEntity> numMap = Maps.newHashMap();

        SoldierTpAllBSearcher searcher = new SoldierTpAllBSearcher(page++, 100);
        searcher.setAdminAreaCode(adminAreaCode);
        List<SoldierTpAllDO> soldierTpAllDOS = soldierTpAllService.searchSocialSecurityInfo(searcher);
        String socialUnemploymentTime = DateUtil.formatDate(org.apache.commons.lang3.time.DateUtils.addMonths(new Date(), -3), "yyyy-MM-dd");

        while (!CollectionUtils.isEmpty(soldierTpAllDOS)) {
            for (SoldierTpAllDO soldierTpAllDO : soldierTpAllDOS) {
                try {
                    log.info("loop：{}, 总数：{}", count++, searcher.getTotalCount());
                    List<SoldierUnemploymentRegistrationInfoDO> registrationInfoDOS = soldierUnemploymentRegistrationInfoService.getByIdCardNoWithDeleted(soldierTpAllDO.getIdCardNo());
                    if (!CollectionUtils.isEmpty(registrationInfoDOS)) {
                        continue;
                    }

                    if (soldierTpAllDO.isSocialSecurityFlag()) {
                        List<InsuredInfoEntity> insuredInfoEntities = ThirdPartyDealUtils.fileSocialSecurity(soldierTpAllDO.getSocialSecurity());
                        if (CollectionUtils.isEmpty(insuredInfoEntities)) {
                            continue;
                        }
                        InsuredInfoEntity lastOne = insuredInfoEntities.get(0);
                        String aae036 = lastOne.getAae036();

                        if (aae036.compareTo(socialUnemploymentTime) < 0) {

                            if (isHasProvinceSocialStatusAndNotGtldz(soldierTpAllDO.getIdCardNo(), soldierTpAllDO.getNickName())) {
                                continue;
                            }

                            log.info("断缴数量：{}", duanjiaoNum++);
                            Boolean studentFlag = null;
                            try {
                                studentFlag = thirdPartyService.isStudent(soldierTpAllDO.getIdCardNo());
                            } catch (DocumentException e) {
                                log.error("获取学生数据失败：{}", e);
                            }
                            statsInfo(numMap, soldierTpAllDO.getIdCardNo(), studentFlag);
                            if (!Boolean.FALSE.equals(studentFlag)) {
                                log.info("学生数量：{}", studentNum++);
                                continue;
                            }
                            String idCardNo = soldierTpAllDO.getIdCardNo();
                            insertUnemploySoldierRegistration(idCardNo, "断缴,上次社保时间：" + aae036, "断缴,上次社保时间：" + aae036, UnemploymentSourceTypeEnum.WITHDRAW.name());
                        }
                    }
                } catch (Exception e) {
                    log.error("导入出错：{}", e);
                }

            }
            searcher = new SoldierTpAllBSearcher(page++, 2000);
            searcher.setAdminAreaCode(adminAreaCode);
            soldierTpAllDOS = soldierTpAllService.searchSocialSecurityInfo(searcher);
        }

        log.info("------------------统计start-----------------------");
        for (String key : numMap.keySet()) {
            NumberEntity numberEntity = numMap.get(key);
            log.info("{},{},{}", key, numberEntity.getAllNum(), numberEntity.getStudentNum());
        }
        log.info("------------------统计end-----------------------");
    }


    @Override
    public BaseResponse<String> syncImportToAutoWarning(String adminAreaCode) {
        ThreadPoolManager.getInstance().submit(new Runnable() {
            @Override
            public void run() {

            }
        });
        return ResponseUtils.buildSuccessResponse("");
    }

    @Override
    public BaseResponse<String> removeCompanySocialSoldier(SoldierUnemploymentRegistrationInfoInsertRequest request) {


        ThreadPoolManager.getInstance().submit(new Runnable() {
            @Override
            public void run() {
                SoldierUnemploymentRegistrationInfoBSearcher innerSearcher = new SoldierUnemploymentRegistrationInfoBSearcher(1, Integer.MAX_VALUE);
                innerSearcher.setSource("INDIVIDUAL_PAYMENT");
                innerSearcher.setStatus("EMPLOYMENT");
                List<SoldierUnemploymentRegistrationInfoDO> search = soldierUnemploymentRegistrationInfoService.search(innerSearcher);
                log.info("删除社保重复的那一批次的老兵-已就业, 总数:{}", search.size());
                int loop = 1;
                for (SoldierUnemploymentRegistrationInfoDO registrationInfoDO : search) {
                    SoldierTpAllDO soldierTpAllDO = soldierTpAllService.getByIdCardNo(registrationInfoDO.getIdCardNo());
                    if (soldierTpAllDO.isSocialSecurityFlag()) {
                        List<InsuredInfoEntity> insuredInfoEntities = ThirdPartyDealUtils.fileSocialSecurity(soldierTpAllDO.getSocialSecurity());
                        String lastTime = "2021-06-02";
                        boolean b = checkSameMonthHasCompanySocial(insuredInfoEntities, lastTime);
                        if (b) {

                            soldierUnemploymentRegistrationInfoService.delete(registrationInfoDO.getId(), "GOV", "chongfu");
                            log.info("删除社保重复的那一批次的老兵-已就业, loop:{}", loop++);
                        }
                    }
                }


            }
        });
        return ResponseUtils.buildSuccessResponse("0");
    }

    @Override
    public BaseResponse<String> removeProvinceSocial(SoldierUnemploymentRegistrationInfoInsertRequest request) {


        ThreadPoolManager.getInstance().submit(new Runnable() {
            @Override
            public void run() {
                final SoldierUnemploymentRegistrationInfoBSearcher soldierUnemploymentRegistrationInfoBSearcher = new SoldierUnemploymentRegistrationInfoBSearcher(1, Integer.MAX_VALUE);
                soldierUnemploymentRegistrationInfoBSearcher.setStatusList(Lists.newArrayList(UnemploymentProcessStatusEnum.INIT.name(), UnemploymentProcessStatusEnum.NO_NEED.name()
                        , UnemploymentProcessStatusEnum.EMPLOYMENT_VISIT.name(), UnemploymentProcessStatusEnum.EMPLOYMENT.name()));

                List<SoldierUnemploymentRegistrationInfoDO> registrationInfoDOS = soldierUnemploymentRegistrationInfoService.listAllUnemploymentSolider(soldierUnemploymentRegistrationInfoBSearcher);
                log.info("删除一批，省社保的，待审核，无就业需求，暂无就业需求和已就业人员:{}", registrationInfoDOS.size());
                int loop = 1;
                int succNum = 1;
                for (SoldierUnemploymentRegistrationInfoDO registrationInfoDO : registrationInfoDOS) {
                    log.info("删除一批，省社保的，loop:{}", loop++);
                    if (isHasProvinceSocialStatusAndNotGtldz(registrationInfoDO.getIdCardNo(), registrationInfoDO.getRealName())) {
                        soldierUnemploymentRegistrationInfoService.delete(registrationInfoDO.getId(), "SSBCW", "admin");
                        log.info("删除一批，删除成功，succNum:{}", succNum++);
                    }
                }
            }
        });
        return ResponseUtils.buildSuccessResponse("0");
    }

    @Override
    public BaseResponse<String> recoverProblemOfNnnnn(SoldierUnemploymentRegistrationInfoInsertRequest request) {


        ThreadPoolManager.getInstance().submit(new Runnable() {
            @Override
            public void run() {
                String socialUnemploymentTime = DateUtil.formatDate(org.apache.commons.lang3.time.DateUtils.addMonths(new Date(), -3), "yyyy-MM-dd");
                List<SoldierUnemploymentRegistrationInfoDO> search = soldierUnemploymentRegistrationInfoService.listAllAutoEmployment();
                log.info("恢复，因为NNNNN问题，引起的已就业问题，并回滚到之前状态：{}", search.size());
                int dealNum = 1;
                int succNum = 1;
                for (SoldierUnemploymentRegistrationInfoDO registrationInfoDO : search) {
                    try {
                        log.info("恢复，因为NNNNN问题，引起的已就业问题，并回滚到之前状态：loop：{}", dealNum++);
                        SoldierTpAllDO soldierTpAllDO = soldierTpAllService.getByIdCardNo(registrationInfoDO.getIdCardNo());

                        if (soldierTpAllDO.isSocialSecurityFlag()) {
                            List<InsuredInfoEntity> insuredInfoEntities = ThirdPartyDealUtils.fileSocialSecurity(soldierTpAllDO.getSocialSecurity());
                            if (CollectionUtils.isEmpty(insuredInfoEntities)) {
                                continue;
                            }

                            InsuredInfoEntity lastOne = insuredInfoEntities.get(0);
                            String aae036 = lastOne.getAae036();

                            String companyName = lastOne.getAab004();
                            boolean hasCompany = checkSameMonthHasCompanySocial(insuredInfoEntities, aae036);
                            if ((hasCompany && aae036.compareTo(socialUnemploymentTime) > 0) || isHasProvinceSocialStatusAndNotGtldz(registrationInfoDO.getIdCardNo(), registrationInfoDO.getRealName())) {
                                if (registrationInfoDO.getSource().equals(UnemploymentSourceTypeEnum.MANUALLY.name())) {

                                    String thatTime = DateUtil.formatDate(registrationInfoDO.getCreateDatetime(), "yyyy-MM");
                                    boolean sameCompany = checkIsSameCompany(insuredInfoEntities, thatTime, companyName);
                                    if (!sameCompany) {
                                        log.info("人工填报，公司一致：{}，{}", thatTime, companyName);
                                        continue;
                                    }
                                } else {
                                    continue;
                                }
                            }

                            List<SoldierRegistrationHistoryDO> soldierRegistrationHistoryDOS = soldierRegistrationHistoryService.listByRegistrationId(registrationInfoDO.getId());
                            if (soldierRegistrationHistoryDOS.size() >= 2) {
                                SoldierRegistrationHistoryDO soldierRegistrationHistoryDO = soldierRegistrationHistoryDOS.get(1);
                                registrationInfoDO.setStatus(soldierRegistrationHistoryDO.getStatus());
                                registrationInfoDO.setModifierType("HHOFNNNN");
                                soldierUnemploymentRegistrationInfoService.update(registrationInfoDO);

                                soldierRegistrationHistoryService.delete(soldierRegistrationHistoryDOS.get(0).getId(), "HHOFNNNN", "admin");
                                log.info("恢复，因为NNNNN问题，已删除：loop：{}", succNum++);
                            }
                        }

                    } catch (Exception e) {
                        log.error("刷新失业登记数据出错，{}", e);
                    }
                }
            }
        });
        return ResponseUtils.buildSuccessResponse("0");
    }

    private void statsInfo(Map<String, NumberEntity> numMap, String idCardNo, Boolean studentFlag) {
        SoldierBasicInfoDO byIdCardNo = soldierBasicInfoService.getByIdCardNo(idCardNo);
        if (byIdCardNo != null) {
            String residentAdminAreaCode = byIdCardNo.getResidentAdminAreaCode();
            String cutAreaCode = AdminAreaCodeUtils.cutAreaCode(residentAdminAreaCode, "3");
            NumberEntity numberEntity = numMap.get(cutAreaCode);
            if (numberEntity == null) {
                numberEntity = new NumberEntity();
                numMap.put(cutAreaCode, numberEntity);
            }
            numberEntity.increaseAllNum();
            if (!Boolean.FALSE.equals(studentFlag)) {
                numberEntity.increaseStudentNum();
            }
        }
    }

    private void insertUnemploySoldierRegistration(String idCardNo, String msgReason, String msgHistory, String source) {
        List<SoldierUnemploymentRegistrationInfoDO> existedList = soldierUnemploymentRegistrationInfoService.getByIdCardNoWithDeleted(idCardNo);
        if (CollectionUtils.isEmpty(existedList)) {
            SoldierBasicInfoDO soldierBasicInfoDO = soldierBasicInfoService.getByIdCardNo(idCardNo);
            if (soldierBasicInfoDO == null) {
                return;
            }

            SoldierUnemploymentRegistrationInfoDO registrationInfoDO = new SoldierUnemploymentRegistrationInfoDO();
            registrationInfoDO.setRealName(soldierBasicInfoDO.getRealName());
            registrationInfoDO.setIdCardNo(idCardNo);
            registrationInfoDO.setSoldierId(soldierBasicInfoDO.getSoldierId());
            registrationInfoDO.setType(UnemploymentRegistrationTypeEnum.SYSTEM.name());
            registrationInfoDO.setNeedCheck(true);
            registrationInfoDO.setVisited(false);
            registrationInfoDO.setReason(msgReason);
            registrationInfoDO.setSource(source);
            registrationInfoDO.setStatus(UnemploymentProcessStatusEnum.INIT.name());
            soldierUnemploymentRegistrationInfoService.insert(registrationInfoDO);

            SoldierRegistrationHistoryDO historyDO = new SoldierRegistrationHistoryDO();
            historyDO.setRegistrationId(registrationInfoDO.getId());
            historyDO.setIdCardNo(registrationInfoDO.getIdCardNo());
            historyDO.setStatus(registrationInfoDO.getStatus());
            historyDO.setRealName(registrationInfoDO.getRealName());
            historyDO.setType(RegistrationHistoryTypeEnum.UNEMPLOYMENT.name());
            historyDO.setNote(msgHistory);
            historyDO.setRemark(msgHistory);
            historyDO.setDealType(UnemploymentRegistrationTypeEnum.SYSTEM.name());
            historyDO.setDealTime(new Date());
            soldierRegistrationHistoryService.insert(historyDO);
        }
    }


    @Transactional
    @Override
    public BaseResponse<Integer> updateSoldierUnemploymentRegistrationInfo(final SoldierUnemploymentRegistrationInfoUpdateRequest updateRequest) {

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(updateRequest, "修改SoldierUnemploymentRegistrationInfo的请求参数不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getId(), "id不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getModifierId(), "操作人不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getModifierType(), "操作人类型不能为空");
            }

            @Override
            public void executeService() {
                SoldierUnemploymentRegistrationInfoDO oldOne = soldierUnemploymentRegistrationInfoService.get(updateRequest.getId());
                oldOne.setLastSalary(updateRequest.getLastSalary());
                oldOne.setPersonalCharacteristics(updateRequest.getPersonalCharacteristics());
                oldOne.setEmploymentIntentions(updateRequest.getEmploymentIntentions());
                oldOne.setEmploymentRequirements(updateRequest.getEmploymentRequirements());
                oldOne.setType(UnemploymentRegistrationTypeEnum.INITIATIVE.name());
                oldOne.setReason(updateRequest.getReason());
                RequestSetUtils.setModifierInfo(oldOne, updateRequest);
                Integer affectRowNum = soldierUnemploymentRegistrationInfoService.update(oldOne);
                ResponseUtils.setupSuccessResponse(baseResponse, affectRowNum);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_UNEMPLOYMENT_REGISTRATION_INFO_UPDATE;
            }
        });
        return baseResponse;
    }

    @Override
    public BaseResponse<String> deleteOrModifyArea(SimpleApiRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getUrl(), "url不能为空");
        String result = "";
        try {
            URL source = new URL(request.getUrl());
            InputStream inputStream = source.openStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            final List<List<Object>> read = reader.read();
            List<Object> objects = read.get(0);

            List<CommonAdminAreaDO> quArea = commonAdminAreaService.listByCodeAndLevel("3301%", 3);
            List<CommonAdminAreaDO> zhenArea = commonAdminAreaService.listByCodeAndLevel("3301%", 4);
            Map<String, String> nameCodeMap = new HashMap<>();
            for (CommonAdminAreaDO commonAdminAreaDO : quArea) {
                nameCodeMap.put(commonAdminAreaDO.getValue(), commonAdminAreaDO.getId());
            }
            for (CommonAdminAreaDO commonAdminAreaDO : zhenArea) {
                nameCodeMap.put(commonAdminAreaDO.getValue(), commonAdminAreaDO.getId());
            }

            for (int i = 1; i < read.size(); i++) {
                String itemLog = "";
                List<Object> item = read.get(i);
                String realName = (String) item.get(0);
                String idCardNo = (String) item.get(1);
                String operation = (String) item.get(2);
                itemLog += item.toString();
                if ("删除".equals(operation)) {
                    List<SoldierUnemploymentRegistrationInfoDO> byIdCardNo = soldierUnemploymentRegistrationInfoService.getByIdCardNo(idCardNo);
                    if (!CollectionUtils.isEmpty(byIdCardNo)) {
                        for (SoldierUnemploymentRegistrationInfoDO registrationInfoDO : byIdCardNo) {
                            soldierUnemploymentRegistrationInfoService.delete(registrationInfoDO.getId(), "", "sysytem");
                        }
                        itemLog += "成功";
                    } else {
                        itemLog += "未找到";
                    }
                }
                if ("地区调整".equals(operation)) {
                    String areaValue = (String) item.get(3);
                    String code = nameCodeMap.get(areaValue);
                    if (code != null) {
                        SoldierBasicInfoDO byIdCardNo = soldierBasicInfoService.getByIdCardNo(idCardNo);
                        if (byIdCardNo != null) {
                            byIdCardNo.setResidentAdminAreaCode(code);
                            soldierBasicInfoService.update(byIdCardNo);
                            itemLog += "成功";
                        } else {
                            itemLog += "人员未找到";
                        }
                    } else {
                        String s = commonAdminAreaProvider.analyseAreaCodeByBasicInfo(areaValue);
                        if (!"3301".equals(AdminAreaCodeUtils.getCutdAreaCode(s))) {
                            SoldierBasicInfoDO byIdCardNo = soldierBasicInfoService.getByIdCardNo(idCardNo);
                            if (byIdCardNo != null) {
                                byIdCardNo.setResidentAdminAreaCode(s);
                                soldierBasicInfoService.update(byIdCardNo);
                                itemLog += s + "成功";
                            } else {
                                itemLog += "人员未找到";
                            }
                        } else {
                            itemLog += "地区码错误未找到";
                        }
                    }
                }

                itemLog += "\r\n";
                log.info(itemLog);
                result += itemLog;
            }

        } catch (BizException e) {
            log.error("导出出错：{}", e);
            throw e;
        } catch (Exception e) {
            log.error("导出出错：{}", e);
            throw new BizException(ErrorCodeEnum.ILLEGAL_PARAM);
        }

        return ResponseUtils.buildSuccessResponse(result);
    }

    @Transactional
    @Override
    public BaseResponse<Integer> checkUnemploymentRegistrationInfo(SoldierUnemploymentRegistrationInfoUpdateRequest updateRequest) {

        BizCheckUtil.checkNotNull(updateRequest, "请求不能为空");
        BizCheckUtil.checkNotNull(updateRequest.getId(), "id不能为空");
        BizCheckUtil.checkNotNull(updateRequest.getPass(), "结果不能为空");

        SoldierUnemploymentRegistrationInfoDO info = soldierUnemploymentRegistrationInfoService.get(updateRequest.getId());
        if (updateRequest.getPass()) {
            info.setStatus(UnemploymentProcessStatusEnum.UNEMPLOYMENT.name());
        } else {
            info.setStatus(UnemploymentProcessStatusEnum.REJECT.name());
        }
        info.setModifierId(updateRequest.getModifierId());
        info.setModifierType(updateRequest.getModifierType());
        info.setRemark(updateRequest.getRemark());
        Integer update = soldierUnemploymentRegistrationInfoService.update(info);

        SoldierRegistrationHistoryDO historyDO = new SoldierRegistrationHistoryDO();
        historyDO.setRegistrationId(info.getId());
        historyDO.setIdCardNo(info.getIdCardNo());
        historyDO.setStatus(info.getStatus());
        historyDO.setRealName(info.getRealName());
        historyDO.setType(RegistrationHistoryTypeEnum.UNEMPLOYMENT.name());
        historyDO.setRemark(updateRequest.getRemark());
        historyDO.setNote((updateRequest.getPass() ? "审核通过:" : "驳回:") + updateRequest.getRemark());
        historyDO.setRemark((updateRequest.getPass() ? "审核通过:" : "驳回:") + updateRequest.getRemark());
        historyDO.setDealType(UnemploymentRegistrationTypeEnum.INITIATIVE.name());
        historyDO.setDealTime(new Date());
        soldierRegistrationHistoryService.insert(historyDO);

        return ResponseUtils.buildSuccessResponse(update);
    }

    @Transactional
    @Override
    public BaseResponse<Integer> setAsRecommend(SoldierUnemploymentRegistrationInfoUpdateRequest updateRequest) {

        BizCheckUtil.checkNotNull(updateRequest, "请求不能为空");
        BizCheckUtil.checkNotBlank(updateRequest.getSoldierId(), "soliderId 不能为空");
        SoldierBasicInfoDO bySoldierId = soldierBasicInfoService.getBySoldierId(updateRequest.getSoldierId());
        if (bySoldierId == null) {
            return ResponseUtils.buildSuccessResponse(0);
        }
        List<SoldierUnemploymentRegistrationInfoDO> list = soldierUnemploymentRegistrationInfoService.getByIdCardNo(bySoldierId.getIdCardNo());
        if (!CollectionUtils.isEmpty(list)) {
            for (SoldierUnemploymentRegistrationInfoDO soldierUnemploymentRegistrationInfoDO : list) {
                if (soldierUnemploymentRegistrationInfoDO.getStatus().equals(UnemploymentProcessStatusEnum.UNEMPLOYMENT.name())) {
                    soldierUnemploymentRegistrationInfoDO.setStatus(UnemploymentProcessStatusEnum.UNEMPLOYMENT.name());


                    SoldierRegistrationHistoryDO oldOne = soldierRegistrationHistoryService.getByRegistrationIdAndStatus(soldierUnemploymentRegistrationInfoDO.getId(), UnemploymentProcessStatusEnum.RECOMMEND.name());
                    if (oldOne != null) {
                        continue;
                    }
                    SoldierRegistrationHistoryDO historyDO = new SoldierRegistrationHistoryDO();
                    historyDO.setRegistrationId(soldierUnemploymentRegistrationInfoDO.getId());
                    historyDO.setIdCardNo(soldierUnemploymentRegistrationInfoDO.getIdCardNo());
                    historyDO.setStatus(UnemploymentProcessStatusEnum.RECOMMEND.name());
                    historyDO.setRealName(soldierUnemploymentRegistrationInfoDO.getRealName());
                    historyDO.setType(RegistrationHistoryTypeEnum.UNEMPLOYMENT.name());
                    historyDO.setRemark("设置为推荐中,浏览相关岗位！");
                    historyDO.setNote("设置为推荐中,浏览相关岗位！");
                    historyDO.setDealType(UnemploymentRegistrationTypeEnum.SYSTEM.name());
                    historyDO.setDealTime(new Date());
                    soldierRegistrationHistoryService.insert(historyDO);

                    soldierUnemploymentRegistrationInfoService.update(soldierUnemploymentRegistrationInfoDO);
                }
            }
        }
        return ResponseUtils.buildSuccessResponse(0);
    }

    @Override
    public BaseResponse<Integer> setAsEmployment(SoldierUnemploymentRegistrationInfoUpdateRequest updateRequest) {

        BizCheckUtil.checkNotNull(updateRequest, "请求不能为空");
        BizCheckUtil.checkNotBlank(updateRequest.getSoldierId(), "soliderId 不能为空");
        SoldierBasicInfoDO bySoldierId = soldierBasicInfoService.getBySoldierId(updateRequest.getSoldierId());
        if (bySoldierId == null) {
            return ResponseUtils.buildSuccessResponse(0);
        }
        List<SoldierUnemploymentRegistrationInfoDO> list = soldierUnemploymentRegistrationInfoService.getByIdCardNo(bySoldierId.getIdCardNo());
        if (!CollectionUtils.isEmpty(list)) {
            for (SoldierUnemploymentRegistrationInfoDO soldierUnemploymentRegistrationInfoDO : list) {
                if (soldierUnemploymentRegistrationInfoDO.getStatus().equals(UnemploymentProcessStatusEnum.UNEMPLOYMENT.name())
                        || soldierUnemploymentRegistrationInfoDO.getStatus().equals(UnemploymentProcessStatusEnum.RECOMMEND.name())) {
                    soldierUnemploymentRegistrationInfoDO.setStatus(UnemploymentProcessStatusEnum.EMPLOYMENT.name());
                    soldierUnemploymentRegistrationInfoDO.setEmploymentDatetime(new Date());
                    SoldierRegistrationHistoryDO historyDO = new SoldierRegistrationHistoryDO();
                    historyDO.setRegistrationId(soldierUnemploymentRegistrationInfoDO.getId());
                    historyDO.setIdCardNo(soldierUnemploymentRegistrationInfoDO.getIdCardNo());
                    historyDO.setStatus(soldierUnemploymentRegistrationInfoDO.getStatus());
                    historyDO.setRealName(soldierUnemploymentRegistrationInfoDO.getRealName());
                    historyDO.setType(RegistrationHistoryTypeEnum.UNEMPLOYMENT.name());
                    historyDO.setRemark(updateRequest.getRemark());
                    historyDO.setNote(updateRequest.getRemark());
                    historyDO.setDealType(UnemploymentRegistrationTypeEnum.SYSTEM.name());
                    historyDO.setDealTime(new Date());
                    soldierRegistrationHistoryService.insert(historyDO);

                    soldierUnemploymentRegistrationInfoService.update(soldierUnemploymentRegistrationInfoDO);
                }
            }
        }
        return ResponseUtils.buildSuccessResponse(0);
    }

    @Override
    public BaseResponse<Integer> autoSetEmploymentBySocialSecurityOfSystem(SoldierUnemploymentRegistrationInfoUpdateRequest updateRequest) {

        int count = 1;
        int page = 1;

        int dealNum = 1;
        Map<String, NumberEntity> numMap = Maps.newHashMap();

        String socialUnemploymentTime = DateUtil.formatDate(org.apache.commons.lang3.time.DateUtils.addMonths(new Date(), -3), "yyyy-MM-dd");
        do {
            final SoldierUnemploymentRegistrationInfoBSearcher soldierUnemploymentRegistrationInfoBSearcher = new SoldierUnemploymentRegistrationInfoBSearcher(page++, 100);
            soldierUnemploymentRegistrationInfoBSearcher.setStatusList(Lists.newArrayList(UnemploymentProcessStatusEnum.UNEMPLOYMENT.name(),
                    UnemploymentProcessStatusEnum.RECOMMEND.name(), UnemploymentProcessStatusEnum.NO_NEED.name(), UnemploymentProcessStatusEnum.EMPLOYMENT_VISIT.name(), UnemploymentProcessStatusEnum.INIT.name()));
            List<SoldierUnemploymentRegistrationInfoDO> soldierUnemploymentRegistrationInfoDOList = soldierUnemploymentRegistrationInfoService.search(soldierUnemploymentRegistrationInfoBSearcher);
            if (CollectionUtils.isEmpty(soldierUnemploymentRegistrationInfoDOList)) {
                break;
            }

            for (SoldierUnemploymentRegistrationInfoDO registrationInfoDO : soldierUnemploymentRegistrationInfoDOList) {
                try {
                    SoldierTpAllDO soldierTpAllDO = soldierTpAllService.getByIdCardNo(registrationInfoDO.getIdCardNo());

                    if (soldierTpAllDO.isSocialSecurityFlag()) {
                        List<InsuredInfoEntity> insuredInfoEntities = ThirdPartyDealUtils.fileSocialSecurity(soldierTpAllDO.getSocialSecurity());
                        if (CollectionUtils.isEmpty(insuredInfoEntities)) {
                            continue;
                        }

                        InsuredInfoEntity lastOne = insuredInfoEntities.get(0);
                        String aae036 = lastOne.getAae036();

                        String companyName = lastOne.getAab004();
                        boolean hasCompany = checkSameMonthHasCompanySocial(insuredInfoEntities, aae036);
                        if ((hasCompany && aae036.compareTo(socialUnemploymentTime) > 0) || isHasProvinceSocialStatusAndNotGtldz(registrationInfoDO.getIdCardNo(), registrationInfoDO.getRealName())) {
                            log.info("从断缴变成缴纳：{}， registrationInfoDO：{}", dealNum++, registrationInfoDO);

                            if (registrationInfoDO.getSource().equals(UnemploymentSourceTypeEnum.MANUALLY.name())) {

                                String thatTime = DateUtil.formatDate(registrationInfoDO.getCreateDatetime(), "yyyy-MM");
                                boolean sameCompany = checkIsSameCompany(insuredInfoEntities, thatTime, companyName);
                                if (sameCompany) {
                                    log.info("人工填报，公司一致：{}，{}", thatTime, companyName);
                                    continue;
                                }
                            }

                            registrationInfoDO.setEmploymentDatetime(new Date());
                            registrationInfoDO.setStatus(UnemploymentProcessStatusEnum.EMPLOYMENT.name());
                            soldierUnemploymentRegistrationInfoService.update(registrationInfoDO);

                            SoldierRegistrationHistoryDO historyDO = new SoldierRegistrationHistoryDO();
                            historyDO.setRegistrationId(registrationInfoDO.getId());
                            historyDO.setIdCardNo(registrationInfoDO.getIdCardNo());
                            historyDO.setStatus(registrationInfoDO.getStatus());
                            historyDO.setRealName(registrationInfoDO.getRealName());
                            historyDO.setType(RegistrationHistoryTypeEnum.UNEMPLOYMENT.name());
                            historyDO.setNote("系统发现,社保状态变更为企业缴费，状态变为已就业");
                            historyDO.setRemark("系统发现,社保状态变更为企业缴费，状态变为已就业");
                            historyDO.setDealType(UnemploymentRegistrationTypeEnum.SYSTEM.name());
                            historyDO.setDealTime(new Date());
                            soldierRegistrationHistoryService.insert(historyDO);
                        }
                    }

                } catch (Exception e) {
                    log.error("刷新失业登记数据出错，{}", e);
                }
            }
        }
        while (true);

        return ResponseUtils.buildSuccessResponse(0);
    }

    private boolean checkIsSameCompany(List<InsuredInfoEntity> insuredInfoEntities, String thatTime, String companyName) {
        List<String> companyNames = Lists.newArrayList();

        for (InsuredInfoEntity insuredInfoEntity : insuredInfoEntities) {
            String aae036 = insuredInfoEntity.getAae036();
            if (aae036.startsWith(thatTime)) {
                companyNames.add(insuredInfoEntity.getAab004());
            }
        }

        if (CollectionUtils.isEmpty(companyNames)) {
            return false;
        }

        if (companyNames.size() > 1) {
            return false;
        }

        if (companyNames.get(0).equals(companyName)) {
            return true;
        }

        return false;
    }

    @Override
    public BaseResponse<Integer> cancelUnemploymentRegistrationInfo(SoldierUnemploymentRegistrationInfoUpdateRequest updateRequest) {

        BizCheckUtil.checkNotNull(updateRequest, "请求不能为空");
        BizCheckUtil.checkNotNull(updateRequest.getId(), "id不能为空");
        SoldierUnemploymentRegistrationInfoDO info = soldierUnemploymentRegistrationInfoService.get(updateRequest.getId());
        info.setStatus(UnemploymentProcessStatusEnum.CANCEL.name());
        info.setAuditRemark(updateRequest.getAuditRemark());
        info.setModifierId(updateRequest.getModifierId());
        info.setModifierType(updateRequest.getModifierType());
        Integer update = soldierUnemploymentRegistrationInfoService.update(info);

        SoldierRegistrationHistoryDO historyDO = new SoldierRegistrationHistoryDO();
        historyDO.setRegistrationId(info.getId());
        historyDO.setIdCardNo(info.getIdCardNo());
        historyDO.setStatus(info.getStatus());
        historyDO.setRealName(info.getRealName());
        historyDO.setType(RegistrationHistoryTypeEnum.UNEMPLOYMENT.name());
        String note = "撤回申请，";
        historyDO.setNote(note);
        historyDO.setRemark(note);
        historyDO.setDealType(UnemploymentRegistrationTypeEnum.INITIATIVE.name());
        historyDO.setDealTime(new Date());
        soldierRegistrationHistoryService.insert(historyDO);
        return ResponseUtils.buildSuccessResponse(update);
    }

    @Override
    public BaseResponse<Integer> findJob(SoldierUnemploymentRegistrationInfoUpdateRequest updateRequest) {

        BizCheckUtil.checkNotNull(updateRequest, "请求不能为空");
        BizCheckUtil.checkNotNull(updateRequest.getId(), "id不能为空");

        SoldierUnemploymentRegistrationInfoDO info = soldierUnemploymentRegistrationInfoService.get(updateRequest.getId());
        info.setStatus(UnemploymentProcessStatusEnum.EMPLOYMENT.name());
        info.setEmploymentDatetime(new Date());
        info.setModifierId(updateRequest.getModifierId());
        info.setModifierType(updateRequest.getModifierType());
        Integer update = soldierUnemploymentRegistrationInfoService.update(info);

        SoldierRegistrationHistoryDO historyDO = new SoldierRegistrationHistoryDO();
        historyDO.setRegistrationId(info.getId());
        historyDO.setIdCardNo(info.getIdCardNo());
        historyDO.setStatus(info.getStatus());
        historyDO.setRealName(info.getRealName());
        historyDO.setType(RegistrationHistoryTypeEnum.UNEMPLOYMENT.name());
        historyDO.setNote("确认已经找到工作");
        historyDO.setRemark(historyDO.getNote());
        historyDO.setDealType(UnemploymentRegistrationTypeEnum.INITIATIVE.name());
        historyDO.setDealTime(new Date());
        soldierRegistrationHistoryService.insert(historyDO);
        return ResponseUtils.buildSuccessResponse(update);
    }

    @Transactional
    @Override
    public BaseResponse<String> sendMessage(SoldierUnemploymentRegistrationInfoUpdateRequest updateRequest) {

        BizCheckUtil.checkNotNull(updateRequest, "请求不能为空");
        BizCheckUtil.checkIsTrue(!CollectionUtils.isEmpty(updateRequest.getIdCardNoList()), "idCardNoList不为空");
        BizCheckUtil.checkNotBlank(updateRequest.getEmployeeId(), "employeeId不能为空");
        String adminAreaCode = govOrgService.getAdminAreaCodeOfEmploy(updateRequest.getEmployeeId());

        Future<String> future = ThreadPoolManager.getInstance().submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                String result = "";
                for (String idCardNo : updateRequest.getIdCardNoList()) {
                    List<SoldierUnemploymentRegistrationInfoDO> registrationInfoDOS = soldierUnemploymentRegistrationInfoService.getByIdCardNo(idCardNo);
                    if (CollectionUtils.isEmpty(registrationInfoDOS)) {
                        continue;
                    }
                    SoldierBasicInfoDO basicInfoDO = soldierBasicInfoService.getByIdCardNo(idCardNo);
                    BizCheckUtil.checkNotNull(basicInfoDO, "查无此人");

                    SoldierUnemploymentRegistrationInfoDO infoDO = registrationInfoDOS.get(0);

                    infoDO.setSendDatetime(new Date());
                    soldierUnemploymentRegistrationInfoService.update(infoDO);

                    String realName = infoDO.getRealName();
                    String title = realName + "存在失业情况，请走访！";

                    String expectedPositionTypeName = "";
                    String expectedIndustryName = "";
                    String expectedSalary = "";
                    JobCandidateResumeDTO resumeDTO = sceneConsumer.getMyResume(basicInfoDO.getSoldierId());
                    if (resumeDTO != null) {
                        String expectedInfo = resumeDTO.getExpectedInfo();
                        if (StringUtils.isNotBlank(expectedInfo)) {
                            List<ExpectedInfoRequest> expectedInfoRequests = JSONArray.parseArray(expectedInfo, ExpectedInfoRequest.class);
                            if (!CollectionUtils.isEmpty(expectedInfoRequests)) {
                                ExpectedInfoRequest expectedInfoRequest = expectedInfoRequests.get(0);
                                expectedPositionTypeName = expectedInfoRequest.getExpectedPositionTypeName();
                                expectedIndustryName = expectedInfoRequest.getExpectedIndustryName();
                                expectedSalary = buildMoneyCN(expectedInfoRequest.getExpectedSalary());
                            }
                        }
                    }

                    CommonAdminAreaDO commonAdminAreaDO = commonAdminAreaService.get(basicInfoDO.getResidentAdminAreaCode());
                    String content = String.format("%s, %s,行政区划:%s, 家庭地址:%s, " +
                                    "个人特长：%s, 其他要求：%s, 失业原因： %s！期望岗位: %s, 期望行业:%s, 期望薪资: %s \n请走访",
                            infoDO.getRealName(),
                            basicInfoDO.getIdCardNo(),
                            commonAdminAreaDO != null ? commonAdminAreaDO.getFullValuePath() : "",
                            basicInfoDO.getResidentAddress(),

                            infoDO.getPersonalCharacteristics() != null ? infoDO.getPersonalCharacteristics() : "",
                            infoDO.getEmploymentRequirements() != null ? infoDO.getEmploymentRequirements() : "",
                            infoDO.getReason() != null ? infoDO.getReason() : "",
                            expectedPositionTypeName,
                            expectedIndustryName,
                            expectedSalary);

                    GovMessageRequest messageRequest = new GovMessageRequest(idCardNo, title, content);
                    messageRequest.setMobile(basicInfoDO.getMobile());
                    messageRequest.setRealName(basicInfoDO.getRealName());
                    messageRequest.setAddress(basicInfoDO.getResidentAddress());

                    BaseResponse<String> stringBaseResponse = govMessageProvider.sendSubFwzMessage(messageRequest, adminAreaCode);
                    result = stringBaseResponse.getDto();
                    log.info("信息结果：{}", result);
                }

                return result;
            }
        });

        String result = "";
        try {
            result = future.get(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
            e.printStackTrace();
            Throwable cause = e.getCause();
            if (cause instanceof BizException) {
                BizException bizException = (BizException) cause;
                throw bizException;
            }
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

        return ResponseUtils.buildSuccessResponse(result);
    }

    private String buildMoneyCN(String expectedSalary) {
        if (Strings.isBlank(expectedSalary)) {
            return "";
        }
        try {
            expectedSalary = expectedSalary.replace("[", "");
            expectedSalary = expectedSalary.replace("]", "");
            String[] split = expectedSalary.split(",");
            Integer salaryRangeMin = Integer.valueOf(split[0]);
            Integer offset = Integer.valueOf(split[1]);
            if (salaryRangeMin == 0) {
                return "面议";
            }
            return salaryRangeMin + "k - " + (salaryRangeMin + offset + 1) + "k";
        } catch (Exception e) {
            log.error("解析错误:{}", e);
        }
        return "";
    }


    @Override
    public BaseResponse<Integer> deleteSoldierUnemploymentRegistrationInfo(final BaseDeleteRequest deleteRequest) {

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(deleteRequest, "逻辑删除SoldierUnemploymentRegistrationInfo的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String) deleteRequest.getId(), "id不能为空");
                BizCheckUtil.checkNotBlank(deleteRequest.getModifierType(), "操作人类型不能为空");
                BizCheckUtil.checkNotBlank((String) deleteRequest.getModifierId(), "操作人不能为空");
            }

            @Override
            public void executeService() {
                final Integer affectRowNum = soldierUnemploymentRegistrationInfoService.delete((String) deleteRequest.getId(), deleteRequest.getModifierType(), (String) deleteRequest.getModifierId());
                ResponseUtils.setupSuccessResponse(baseResponse, affectRowNum);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_UNEMPLOYMENT_REGISTRATION_INFO_DELETE_LOGICALLY;
            }
        });
        return baseResponse;
    }

    @Override
    public BaseResponse<String> asycExportRegistrationInfo(SoldierUnemploymentRegistrationInfoSearchRequest searchRequest) {


        CommonTmpInfoDO infoDO = new CommonTmpInfoDO();
        infoDO.setTitle("一人一档导出");
        commonTmpInfoService.insert(infoDO);

        ThreadPoolManager.getInstance().submit(new Runnable() {
            @Override
            public void run() {
                try {
                    searchRequest.setPageNo(1);
                    searchRequest.setPageSize(Integer.MAX_VALUE);
                    List<SoldierUnemploymentRegistrationInfoDTO> dto = searchSoldierUnemploymentRegistrationInfo(searchRequest).getDto();
                    List<String> headers = Lists.newArrayList("姓名", "身份证", "行政区划", "家庭地址", "手机号", "最近缴费单位", "失业原因", "就业意向");

                    List<List<String>> data = Lists.newArrayList();
                    if (!CollectionUtils.isEmpty(dto)) {
                        for (SoldierUnemploymentRegistrationInfoDTO registrationInfoDTO : dto) {
                            List<String> item = Lists.newArrayList();
                            item.add(registrationInfoDTO.getRealName());
                            item.add(registrationInfoDTO.getIdCardNo());

                            SoldierBasicInfoDO byIdCardNo = soldierBasicInfoService.getByIdCardNo(registrationInfoDTO.getIdCardNo());
                            if (byIdCardNo != null) {
                                CommonAdminAreaDO commonAdminAreaDO = commonAdminAreaService.get(byIdCardNo.getResidentAdminAreaCode());
                                if (commonAdminAreaDO != null) {
                                    item.add(commonAdminAreaDO.getFullValuePath());
                                } else {
                                    item.add("");
                                }
                                item.add(byIdCardNo.getResidentAddress());
                                item.add(byIdCardNo.getMobile());
                            } else {
                                item.add("");
                                item.add("");
                                item.add("");
                            }
                            InsuredEntity insuredEntity = soldierBasicInfoProvider.querySocialSecurity2(registrationInfoDTO.getIdCardNo(), registrationInfoDTO.getRealName()).getDto();
                            item.add(insuredEntity.getDwmc() + ":" + insuredEntity.getYbzxbz());
                            item.add(registrationInfoDTO.getReason());

                            if (byIdCardNo != null && Strings.isNotBlank(byIdCardNo.getSoldierId())) {
                                JobCandidateResumeDTO resumeDTO = sceneConsumer.getMyResume(byIdCardNo.getSoldierId());
                                if (resumeDTO != null) {
                                    String expectedInfo = resumeDTO.getExpectedInfo();
                                    if (StringUtils.isNotBlank(expectedInfo)) {
                                        List<ExpectedInfoRequest> expectedInfoRequests = JSONArray.parseArray(expectedInfo, ExpectedInfoRequest.class);
                                        if (!CollectionUtils.isEmpty(expectedInfoRequests)) {
                                            ExpectedInfoRequest expectedInfoRequest = expectedInfoRequests.get(0);
                                            String expectedPositionTypeName = expectedInfoRequest.getExpectedPositionTypeName();
                                            String expectedIndustryName = expectedInfoRequest.getExpectedIndustryName();
                                            String expectedSalary = buildMoneyCN(expectedInfoRequest.getExpectedSalary());
                                            item.add("期望岗位：" + expectedPositionTypeName + ", 期望行业：" + expectedIndustryName + ", 期望薪资:" + expectedSalary);
                                        } else {
                                            item.add("");
                                        }
                                    } else {
                                        item.add("");
                                    }
                                } else {
                                    item.add("");
                                }
                            } else {
                                item.add("");
                            }


                            data.add(item);
                        }
                    }
                    ExcelResultBO excelResultBO = new ExcelResultBO("导出就业需求", headers, data);

                    infoDO.setContent(JSON.toJSONString(excelResultBO));
                    infoDO.setUsed(false);
                    commonTmpInfoService.update(infoDO);
                } catch (Exception e) {
                    log.error("{}", e);
                }
            }
        });

        return ResponseUtils.buildSuccessResponse(infoDO.getId());
    }

    @Override
    public BasePagingResponse<List<SoldierUnemploymentRegistrationInfoDTO>> searchOpenUnemploymentRegistrationInfo(SoldierUnemploymentRegistrationInfoSearchRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotBlank(request.getAuth(), "auth不能为空");

        String adminAreaCode = commonAuthInfoProvider.getAdminAreaCode(request.getAuth());
        final SoldierUnemploymentRegistrationInfoBSearcher soldierUnemploymentRegistrationInfoBSearcher = SoldierUnemploymentRegistrationInfoProviderConverter.convertRequestSO2Searcher(request);
        soldierUnemploymentRegistrationInfoBSearcher.setAdminAreaCode(AdminAreaCodeUtils.getCutdAreaCode(adminAreaCode));
        final List<SoldierUnemploymentRegistrationInfoDO> soldierUnemploymentRegistrationInfoDOList = soldierUnemploymentRegistrationInfoService.search(soldierUnemploymentRegistrationInfoBSearcher);
        final List<SoldierUnemploymentRegistrationInfoDTO> soldierUnemploymentRegistrationInfoDTOList = SoldierUnemploymentRegistrationInfoProviderConverter.convertResponseDOList2DTOList(soldierUnemploymentRegistrationInfoDOList);
        if (!CollectionUtils.isEmpty(soldierUnemploymentRegistrationInfoDTOList)) {
            for (SoldierUnemploymentRegistrationInfoDTO item : soldierUnemploymentRegistrationInfoDTOList) {
                item.setAreaValue(getCachedAreaValue(item.getIdCardNo()));

                if (UnemploymentProcessStatusEnum.INIT.name().equals(item.getStatus()) ||
                        UnemploymentProcessStatusEnum.UNEMPLOYMENT.name().equals(item.getStatus())) {
                    item.setColour("red");
                } else if (UnemploymentProcessStatusEnum.NO_NEED.name().equals(item.getStatus())
                        || UnemploymentProcessStatusEnum.EMPLOYMENT_VISIT.name().equals(item.getStatus())
                        || UnemploymentProcessStatusEnum.EMPLOYMENT_SOCIAL.name().equals(item.getStatus())) {
                    item.setColour("yellow");
                } else {
                    item.setColour("green");
                }
            }
        }
        return ResponseUtils.buildSuccessPagingResponse(soldierUnemploymentRegistrationInfoDTOList, soldierUnemploymentRegistrationInfoBSearcher);
    }

    @Override
    public BasePagingResponse<List<SoldierUnemploymentRegistrationInfoDTO>> soldierJobEmployment(CommonLedgerStatsRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getAdminAreaCode(), "地区码不能为空");

        boolean b = request.convertTime();
        if (!b) {
            return ResponseUtils.buildSuccessPagingResponse(null);
        }
        SoldierUnemploymentRegistrationInfoBSearcher searcher = new SoldierUnemploymentRegistrationInfoBSearcher(request.getPageNo(), request.getPageSize());
        searcher.setAdminAreaCode(AdminAreaCodeUtils.getCutdAreaCode(request.getAdminAreaCode()));
        searcher.setStartTime(request.getStartTime());
        searcher.setEndTime(request.getEndTime());
        searcher.setTimeType("employmentDatetime");
        searcher.setStatus(UnemploymentProcessStatusEnum.EMPLOYMENT.name());
        searcher.setSortKeyValueJoint("a.createDatetime_desc");
        final List<SoldierUnemploymentRegistrationInfoDO> soldierUnemploymentRegistrationInfoDOList = soldierUnemploymentRegistrationInfoService.search(searcher);
        final List<SoldierUnemploymentRegistrationInfoDTO> soldierUnemploymentRegistrationInfoDTOList = SoldierUnemploymentRegistrationInfoProviderConverter.convertResponseDOList2DTOList(soldierUnemploymentRegistrationInfoDOList);
        for (SoldierUnemploymentRegistrationInfoDTO registrationInfoDTO : soldierUnemploymentRegistrationInfoDTOList) {
            fillRegistrationInfo(registrationInfoDTO);
        }
        return ResponseUtils.buildSuccessPagingResponse(soldierUnemploymentRegistrationInfoDTOList, searcher);
    }

    private void fillRegistrationInfo(SoldierUnemploymentRegistrationInfoDTO registrationInfoDTO) {
        if (registrationInfoDTO.getEmploymentDatetime() == null) {
            List<SoldierRegistrationHistoryDO> soldierRegistrationHistoryDOS = soldierRegistrationHistoryService.listByStatus(registrationInfoDTO.getIdCardNo(), UnemploymentProcessStatusEnum.EMPLOYMENT.name());
            if (!CollectionUtils.isEmpty(soldierRegistrationHistoryDOS)) {
                registrationInfoDTO.setEmploymentDatetime(soldierRegistrationHistoryDOS.get(0).getCreateDatetime());
            }
        }

        SoldierBasicInfoDO byIdCardNo = soldierBasicInfoService.getByIdCardNo(registrationInfoDTO.getIdCardNo());
        if (byIdCardNo != null) {
            registrationInfoDTO.setGender(byIdCardNo.getGender());
            registrationInfoDTO.setMobile(byIdCardNo.getMobile());
            registrationInfoDTO.setResidentAddress(byIdCardNo.getResidentAddress());
        }
    }

    @Override
    public BasePagingResponse<List<SoldierUnemploymentRegistrationInfoDTO>> bgResolveToEmployment(CommonLedgerStatsRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getAdminAreaCode(), "地区码不能为空");

        boolean b = request.convertTime();
        if (!b) {
            return ResponseUtils.buildSuccessPagingResponse(null);
        }
        SoldierUnemploymentRegistrationInfoBSearcher searcher = new SoldierUnemploymentRegistrationInfoBSearcher(1, Integer.MAX_VALUE);
        searcher.setStartTime(request.getStartTime());
        searcher.setEndTime(request.getEndTime());
        searcher.setTimeType("employmentDatetime");
        searcher.setStatus(UnemploymentProcessStatusEnum.EMPLOYMENT.name());
        searcher.setSortKeyValueJoint("a.createDatetime_desc");
        searcher.setAdminAreaCode(AdminAreaCodeUtils.getCutdAreaCode(request.getAdminAreaCode()));
        final List<SoldierUnemploymentRegistrationInfoDO> soldierUnemploymentRegistrationInfoDOList = soldierUnemploymentRegistrationInfoService.search(searcher);
        if (CollectionUtils.isEmpty(soldierUnemploymentRegistrationInfoDOList)) {
            return ResponseUtils.buildSuccessPagingResponse(null);
        }
        CompanyEntryApplySearchRequest companyEntryApplySearchRequest = new CompanyEntryApplySearchRequest(1, Integer.MAX_VALUE);
        companyEntryApplySearchRequest.setAdminAreaCode(request.getAdminAreaCode());
        List<CompanyEntryApplyDTO> dto = sceneConsumer.searchCompanyEntryApply(companyEntryApplySearchRequest).getDto();
        Set<String> companyNameSet = dto.stream().map(CompanyEntryApplyDTO::getName).collect(Collectors.toSet());

        List<String> idCardNoList = soldierUnemploymentRegistrationInfoDOList.stream().map(s -> s.getIdCardNo()).collect(Collectors.toList());

        List<String> matchedIdCardNos = Lists.newArrayList();
        List<SoldierTpAllDO> soldierTpAllDOS = soldierTpAllService.listSocialSecurityByIdCardNoList(idCardNoList);
        Map<String, String> idCardNo2CompanyNameMap = Maps.newHashMap();
        for (SoldierTpAllDO soldierTpAllDO : soldierTpAllDOS) {
            List<InsuredInfoEntity> insuredInfoEntities = ThirdPartyDealUtils.fileSocialSecurity(soldierTpAllDO.getSocialSecurity());
            if (CollectionUtils.isEmpty(insuredInfoEntities)) {
                continue;
            }
            InsuredInfoEntity lastOne = insuredInfoEntities.get(0);
            String lastCompany = lastOne.getAab004();
            if (companyNameSet.contains(lastCompany)) {
                idCardNo2CompanyNameMap.put(soldierTpAllDO.getIdCardNo(), lastCompany);
                matchedIdCardNos.add(soldierTpAllDO.getIdCardNo());
            }
        }

        List<SoldierUnemploymentRegistrationInfoDO> matched = soldierUnemploymentRegistrationInfoDOList.stream().filter(s -> matchedIdCardNos.contains(s.getIdCardNo())).collect(Collectors.toList());

        searcher.setPageSize(request.getPageSize());
        searcher.setTotalCount(matched.size());
        matched = PageUtils.paging(request.getPageNo(), request.getPageSize(), matched);
        final List<SoldierUnemploymentRegistrationInfoDTO> soldierUnemploymentRegistrationInfoDTOList = SoldierUnemploymentRegistrationInfoProviderConverter.convertResponseDOList2DTOList(matched);
        if (!CollectionUtils.isEmpty(soldierUnemploymentRegistrationInfoDTOList)) {
            for (SoldierUnemploymentRegistrationInfoDTO registrationInfoDTO : soldierUnemploymentRegistrationInfoDTOList) {
                fillRegistrationInfo(registrationInfoDTO);
                registrationInfoDTO.setCompanyName(idCardNo2CompanyNameMap.get(registrationInfoDTO.getIdCardNo()));
            }
        }
        return ResponseUtils.buildSuccessPagingResponse(soldierUnemploymentRegistrationInfoDTOList, searcher);
    }

    @Override
    public BasePagingResponse<List<SoldierUnemploymentRegistrationInfoDTO>> searchLongTimeUnsolvedInfo(CommonLedgerStatsRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getAdminAreaCode(), "地区码不能为空");

        boolean b = request.convertTime();
        if (!b) {
            return ResponseUtils.buildSuccessPagingResponse(null);
        }

        SoldierUnemploymentRegistrationInfoBSearcher searcher = new SoldierUnemploymentRegistrationInfoBSearcher(request.getPageNo(), request.getPageSize());
        searcher.setAdminAreaCode(request.getAdminAreaCode());
        searcher.setStartTime(request.getStartTime());
        searcher.setEndTime(request.getEndTime());
        searcher.setTimeType("createDatetime");
        searcher.setStatusList(Lists.newArrayList(UnemploymentProcessStatusEnum.INIT.name(), UnemploymentProcessStatusEnum.UNEMPLOYMENT.name(), UnemploymentProcessStatusEnum.RECOMMEND.name()));
        searcher.setSortKeyValueJoint("a.createDatetime_desc");
        searcher.setLostJobDays(90);

        final List<SoldierUnemploymentRegistrationInfoDO> soldierUnemploymentRegistrationInfoDOList = soldierUnemploymentRegistrationInfoService.search(searcher);
        final List<SoldierUnemploymentRegistrationInfoDTO> soldierUnemploymentRegistrationInfoDTOList = SoldierUnemploymentRegistrationInfoProviderConverter.convertResponseDOList2DTOList(soldierUnemploymentRegistrationInfoDOList);
        for (SoldierUnemploymentRegistrationInfoDTO registrationInfoDTO : soldierUnemploymentRegistrationInfoDTOList) {
            fillRegistrationInfo(registrationInfoDTO);
        }
        return ResponseUtils.buildSuccessPagingResponse(soldierUnemploymentRegistrationInfoDTOList, searcher);
    }

    @Override
    public BaseResponse<String> queryFlexibleEmployment(SimpleApiRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getUrl(), "url不能为空");

        try {
            String url = request.getUrl();
            url = url.replace("115.227.32.11", "172.18.102.62");
            URL source = new URL(url);
            InputStream inputStream = source.openStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            final List<List<Object>> read = reader.read();

            ThreadPoolManager.getInstance().submit(new Runnable() {

                @Override
                public void run() {
                    List<String> result = Lists.newArrayList();
                    for (int i = 1; i < read.size(); i++) {
                        try {
                            List<Object> objects = read.get(i);
                            String name = objects.get(0).toString();
                            String idCardNo = objects.get(1).toString();

                            List<FlexibleEmploymentEntity> flexibleEmploymentEntities = thirdPartyService.queryFlexibleEmployment(name, idCardNo);
                            if (!CollectionUtils.isEmpty(flexibleEmploymentEntities)) {
                                FlexibleEmploymentEntity flexibleEmploymentEntity = flexibleEmploymentEntities.get(0);
                                result.add(String.format("%s,A%s,%s,%d", name, idCardNo, flexibleEmploymentEntity.getBel_strt(), flexibleEmploymentEntity.getAllwnc_amt()));
                            }
                        } catch (Exception e) {
                            log.error("{}", e);
                        }
                    }

                    log.info("灵活就业结果:size:{}", result.size());
                    for (String s : result) {
                        log.info("灵活就业结果-----:{}", s);
                    }
                }
            });

        } catch (Exception e) {
            log.error("{}", e);
        }
        return ResponseUtils.buildSuccessResponse("");

    }

    @Override
    public BaseResponse<String> queryStudent(SimpleApiRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotNull(request.getUrl(), "url不能为空");

        try {
            String url = request.getUrl();
            url = url.replace("115.227.32.11", "172.18.102.62");
            URL source = new URL(url);
            InputStream inputStream = source.openStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream);
            final List<List<Object>> read = reader.read();

            ThreadPoolManager.getInstance().submit(new Runnable() {

                @Override
                public void run() {
                    List<String> result = Lists.newArrayList();
                    for (int i = 1; i < read.size(); i++) {
                        try {
                            List<Object> objects = read.get(i);
                            String name = objects.get(0).toString();
                            String idCardNo = objects.get(1).toString();

                            ProvinceMedicalInsuranceEntity provinceMedicalInsuranceEntity = irsService.queryPersonMedicalInsurance(name, idCardNo);
                            if (provinceMedicalInsuranceEntity != null && provinceMedicalInsuranceEntity.getPsnInsuredInfo() != null
                                    && "大学生".equals(provinceMedicalInsuranceEntity.getPsnInsuredInfo().getPsnType())) {
                                result.add(String.format("%s,A%s,%s,%s", name, idCardNo, provinceMedicalInsuranceEntity.getPsnInsuredInfo().getEmpName(), provinceMedicalInsuranceEntity.getPsnInsuredInfo().getInsuAdmdvs()));
                            }

                        } catch (Exception e) {
                            log.error("{}", e);
                        }
                    }

                    log.info("大学生情况:size:{}", result.size());
                    for (String s : result) {
                        log.info("大学生情况-----:{}", s);
                    }
                }
            });

        } catch (Exception e) {
            log.error("{}", e);
        }
        return ResponseUtils.buildSuccessResponse("");
    }

}
